package com.lpgu.auth.server.service.impl;


import com.lpgu.auth.server.model.SysUserEntity;
import com.lpgu.auth.server.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsManager {

    @Resource
    private SysUserService sysUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUserEntity sysUserEntity = sysUserService.selectByUsername(username);
        List<SimpleGrantedAuthority> grantedAuthorityList = Arrays.asList("USER").stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        return new User(username,sysUserEntity.getPassword(),grantedAuthorityList);
    }

    @Override
    public void createUser(UserDetails user) {
        SysUserEntity sysUserEntity = sysUserService.selectByUsername(user.getUsername());
        if (sysUserEntity != null) {
            throw new RuntimeException("用户名已存在");
        }
        sysUserEntity = new SysUserEntity();
        sysUserEntity.setUsername(user.getUsername());
        sysUserEntity.setPassword(passwordEncoder.encode(user.getPassword()));
        sysUserService.createUser(sysUserEntity);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }
}
